String.prototype.trim = function() {
	//return this.replace(/(^\s*)|(\s*$)/g, "");
	return jQuery.trim(this);
};
String.prototype.replaceAll = function(s1,s2){
	return this.replace(new RegExp(s1,"gm"),s2);
};
Date.prototype.format = function(fmt) { 
    var o = { 
       "m+" : this.getMonth()+1,                 //月份 
       "d+" : this.getDate(),                    //日 
       "h+" : this.getHours(),                   //小时 
       "i+" : this.getMinutes(),                 //分 
       "s+" : this.getSeconds(),                 //秒 
       "q+" : Math.floor((this.getMonth()+3)/3), //季度 
       "S"  : this.getMilliseconds()             //毫秒 
   }; 
   if(/(y+)/.test(fmt)) {
           fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
   }
    for(var k in o) {
       if(new RegExp("("+ k +")").test(fmt)){
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
        }
    }
   return fmt; 
};
//日期格式转换
function dateConvert(oldDateString,format){
	if(_.isEmpty(oldDateString)){
		return "";
	}
	if(_.isEmpty(format)){
		format = "yyyy-mm-dd";
	}
	return new Date(oldDateString).format(format);
};
function timeago(dateStr){
	if(_.isEmpty(dateStr)){
		return "";
	}
	return $.timeago(new Date(dateStr));
}
jQuery.prototype.serializeObject = function() {
	var obj = new Object();
	$.each(this.serializeArray(), function(index, param) {
		if (!(param.name in obj)) {
			obj[param.name] = param.value;
		}
	});
	return obj;
};
//判断浏览器是否支持图片的base64
var isSupportBase64 = ( function() {
    var data = new Image();
    var support = true;
    data.onload = data.onerror = function() {
        if( this.width != 1 || this.height != 1 ) {
            support = false;
        }
    }
    data.src = "";
    return support;
} )();
var isSupportTransition = (function(){
    var s = document.createElement('p').style,
    r = 'transition' in s ||  'WebkitTransition' in s || 'MozTransition' in s || 'msTransition' in s || 'OTransition' in s;
	s = null;
	return r;
})();
function getTagName(obj){
	if(!_.isObject(obj))return "";
	return $(obj).prop("tagName").toLowerCase();
}
function uuid() {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";
 
    var uuid = s.join("");
    return uuid;
};
function guid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
        return v.toString(16);
    });
};
//此平台中，输入项的ID有特殊字符，需转议
function jid(id){
	if(_.isEmpty(id))return null;
	return $("#"+escapeJquery(id));
}
//JQuery中的id选择器含有特殊字符时，不能选中dom元素的解决方法
function escapeJquery(srcString){
    var escapseResult = srcString;// 转义之后的结果
    var jsSpecialChars = ["\\", "^", "$", "*", "?", ".", "+", "(", ")", "[",  "]", "|", "{", "}"];// javascript正则表达式中的特殊字符
    var jquerySpecialChars = ["~", "`", "@", "#", "%", "&", "=", "'", "\"", ":", ";", "<", ">", ",", "/"];// jquery中的特殊字符,不是正则表达式中的特殊字符
    for (var i = 0; i < jsSpecialChars.length; i++) {
        escapseResult = escapseResult.replace(new RegExp("\\" + jsSpecialChars[i], "g"), "\\" + jsSpecialChars[i]);
    }
    for (var i = 0; i < jquerySpecialChars.length; i++) {
        escapseResult = escapseResult.replace(new RegExp(jquerySpecialChars[i], "g"), "\\" + jquerySpecialChars[i]);
    }
    return escapseResult;
}

function isJQuery(obj) {
	if (_.isUndefined(obj)) {
		return false;
	}
	if (obj instanceof jQuery) {
		return true;
	}
	return false;
};
function isImage(val) {
	if (_.isString(val)) {
		return /\.(gif|jpg|jpeg|png|bmp)$/.test(val.toLowerCase());
	}
	return false;
};
function getFileExt(filename){
	if (!_.isString(filename))return null;
    var ext = null;
    var filename = filename.toLowerCase();
    var i = filename.lastIndexOf(".");
    if(i > -1){
    	ext = filename.substring(i+1);
    }
    return ext;
};
function getFunction(obj) {
	obj = trim(obj);
	if ("" != obj) {
		try {
			var fun = eval(obj);
			if(_.isFunction(fun)) return fun;
		} catch (e) {
		}
	}
	return null;
};
function trim(obj, defaultVal) {
	if (_.isUndefined(defaultVal)) {
		defaultVal = "";
	}
	if (_.isUndefined(obj) || _.isNull(obj) || _.isNaN(obj)) {
		return defaultVal;
	}
	if (_.isString(obj)) {
		return obj.trim();
	}
	return obj;
};
// 添加时间戳 解决浏览器缓存
function urlTimestamp(url) {
	var times = new Date().getTime();
	if (url.indexOf("?") > -1) {
		url = url + "&_t=" + times
	} else {
		url = url + "?_t=" + times
	}
	return url;
};
function isReadonly(obj) {
	obj = $(obj);
	var r = obj.prop("readonly");
	var d = obj.prop("disabled");
	if (_.isUndefined(r) && _.isUndefined(d))
		return false;
	return r || d;
};
function waitLoading(flag) {
	if (flag) {
		$("#loading-container").show();
	} else {
		$("#loading-container").hide();
	}
};
function showMsg(msg, type, timeout) {
	toastr.options.closeButton = true;
	if (!_.isNumber(timeout))
		toastr.options.timeOut = timeout;
	type = trim(type, "info");
	if ("success" == type) {
		toastr.success(msg);
	} else if ("warning" == type) {
		toastr.warning(msg);
	} else if ("error" == type) {
		toastr.error(msg);
	} else {
		toastr.info(msg);
	}
};
function setIframeHeight(iframe) {
	if (iframe) {
		var iframeWin = iframe.contentWindow
				|| iframe.contentDocument.parentWindow;
		if (iframeWin.document.body) {
			iframe.height = iframeWin.document.documentElement.scrollHeight
					|| iframeWin.document.body.scrollHeight;
		}
	}
};
//加载网页内容
function loadUri(targetId,uri,callback){
	waitLoading(true);
	$("#"+targetId).load(uri, function(response, status, xhr) {
		if ("success" != status) {
			showMsg("系统异常！", "error");
			console.log("status=" + status + "[" + response + "]");
		} else {
			setTimeout(function(){new autoEventListener($("#"+targetId),true);}, 200);
			if(_.isFunction(callback)){
				callback.call(this,response, status, xhr);
			};
		}
		waitLoading(false);
	});
};
/**
 * post提交数据
 * 
 * @param uri
 * @param datas
 * @param callback
 */
function postData(uri, datas, options, callback,dataType) {
	waitLoading(true);
	if(_.isUndefined(dataType)){
		dataType = "json";
	}
	$.post(uri, datas, function(data) {
		if (_.isFunction(callback)) {
			callback(data,options);
		}
		if(dataType == "json"){
			showMsg(trim(data.msg,"未知异常"),data.success?"success":"error");
		}
		waitLoading(false);
	},dataType).error(function(e) {
		waitLoading(false);
		showMsg("系统异常：" + e.statusText,"error");
	});
};

function postValidatorForm(form, callback) {
	var $form = form;
	if(_.isEmpty(form)){
		showMsg("表单不能为空", "error");
		return;
	}else if(_.isString(form)){//formId
		$form=$("#"+form);
	}else if(!isJQuery(form)){
		$form=$(form);
	};
	//如果有文件上传组件，提示文件先上传
	var fileSuccess = true;
	$("div.uploader").each(function(){
		var $file=$(this);
		if($file.find("li:not(.state-complete)").length>0){
			showMsg($file.attr("title")+"上传未完成，请稍候重试！", "error");
			$file.find("div.uploadBtn").trigger("click");
			fileSuccess=false;
		}
	});
	if(!fileSuccess){
		return;
	};
	var bootstrapValidator = $form.data("bootstrapValidator");
	if (null != bootstrapValidator) {
		bootstrapValidator.validate();
		if (!bootstrapValidator.isValid()) {
			showMsg("表单验证失败", "error");
			return;
		}
	}
	var onsubmit=getFunction($form.data("interceptor"));
	if(onsubmit!=null){
		if(!onsubmit.call()){
			console.log(onsubmit);
			showMsg("系统提交错误，请检查!", "error");
			return;
		}
	}
	var datas = $form.serializeArray();
	postData($form.attr("action"), datas,bootstrapValidator, function(res,bootstrapValidator){
		if (!res.success&&null!=bootstrapValidator) {//后台验证失败
			for (i in res.data) {
				var err=res.data[i];
				var validatorName="notEmpty";
				if(err.type=="Length"){
					validatorName="stringLength";
				}
				try{ bootstrapValidator.updateStatus(err.field, bootstrapValidator.STATUS_INVALID, validatorName);}catch(e){console.error("脚本异常:"+e.message); }
				if(validatorName=="stringLength"){
					try{ bootstrapValidator.updateMessage(err.field, validatorName, $.fn.bootstrapValidator.helpers.format(options.message || $.fn.bootstrapValidator.i18n.stringLength.less, parseInt(err.msg)));}catch(e){console.error("脚本异常:"+e.message); }
				}
			}
		}
		if (_.isFunction(callback)) {
			callback(res);
		}
	});
};
//js设置的输入框值，bootstrapValidator不能自动验证，需主动调用清除验证
function resetValidateField(field,form){
	if(!isJQuery(field)){
		field=$(field);
	}
	var bvField=field.attr("data-bv-field");
	if(_.isEmpty(bvField))return;
	if(_.isEmpty(form)){
		form=field.parents("form.bv-form");
	}else if(_.isString(form)){//formId
		form=$("#"+form);
	}else if(!isJQuery(form)){
		form=$(form);
	}
	if(form.length<1)return;
	var bootstrapValidator=form.data('bootstrapValidator');
	if(_.isEmpty(bootstrapValidator))return;
		try{ bootstrapValidator.updateStatus(bvField, bootstrapValidator.STATUS_NOT_VALIDATED,null).validateField(bvField); }catch(e){console.error("脚本异常:"+e.message); }
}